<?php
session_start();

if ( $_SESSION['manager'] )
{
    require_once('../inc/config.db.php');

    switch ( $_GET['dictionary'] )
    {
	case	'groups':
	    $_GET['id'] = preg_replace('/^group_(\d+)$/','$1',$_GET['id']);
	    switch ( $_GET['action'] )
	    {
		case	'add':
		    if ( isset($_GET['name']) )
		    {
			mysql_query(sprintf('INSERT INTO `group` SET `group_name`=\'%s\'',mysql_escape_string($_GET['name'])));
			if ( mysql_affected_rows()==1 )
			{
			    print json_encode(array('code'=>200));
			}
			else
			{
			    print json_encode(array('code'=>500,'text'=>mysql_error()));
			}
		    }
		    break;

		case	'delete':
		    if ( isset($_GET['id']) )
		    {
			$result = mysql_query('SELECT `id` FROM `customer` WHERE `group_id`='.$_GET['id']);
			if ( mysql_affected_rows()==0 )
			{
			    mysql_query('DELETE FROM `group` WHERE `id`='.$_GET['id']);
			    print json_encode(array('code'=>200));
			}
			else
			if ( mysql_affected_rows()>0 )
			{
			    print json_encode(array('code'=>500,'text'=>"Группа не пуста.\nПереведите всех клиентов в другую группу!"));
			}
			else
			{
			    print json_encode(array('code'=>500,'text'=>mysql_error()));
			}
		    }
		    break;
	    }
	    break;

	case	'statuses':
	    $_GET['id'] = preg_replace('/^status_(\d+)$/','$1',$_GET['id']);
	    switch ( $_GET['action'] )
	    {
		case	'add':
		    if ( isset($_GET['name']) )
		    {
			mysql_query(sprintf('INSERT INTO `status` SET `status_name`=\'%s\'',mysql_escape_string($_GET['name'])));
			if ( mysql_affected_rows()==1 )
			{
			    print json_encode(array('code'=>200));
			}
			else
			{
			    print json_encode(array('code'=>500,'text'=>mysql_error()));
			}
		    }
		    break;

		case	'delete':
		    if ( isset($_GET['id']) )
		    {
			$result = mysql_query('SELECT `id` FROM `customer` WHERE `status_id`='.$_GET['id']);
			if ( mysql_affected_rows()==0 )
			{
			    mysql_query('DELETE FROM `status` WHERE `id`='.$_GET['id']);
			    print json_encode(array('code'=>200));
			}
			else
			if ( mysql_affected_rows()>0 )
			{
			    print json_encode(array('code'=>500,'text'=>"В базе данных есть клиенты с этим статусом.\nСмените им статус и повторите удаление."));
			}
			else
			{
			    print json_encode(array('code'=>500,'text'=>mysql_error()));
			}
		    }
		    break;
	    }
	    break;
    }
}
?>
